package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.PrivateStoryAdapter;
import com.jdy.haoduoaiteacher.enums.MediaType;
import com.jdy.haoduoaiteacher.enums.PlayState;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.intface.IMParseListener;
import com.jdy.haoduoaiteacher.model.CarlaClassicVo;
import com.jdy.haoduoaiteacher.model.LeHotRecomStory;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoaiteacher.pulltorefresh.PullableGridView;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.OnDataReceivedListener;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.view.RippleView;
import com.jdy.haoduoaiteacher.view.RippleView.OnRippleCompleteListener;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

//import com.jdy.haoduoaiteacher.util.ImHelper;
//import com.tencent.TIMConnListener;
//import com.tencent.TIMManager;

public class PrivateStoryActivity extends BaseActivity implements
        OnRefreshListener, OnItemClickListener, IMParseListener,
        OnDataReceivedListener {

  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.content_views)
  private PullableGridView gridView;

  @InjectView(id = R.id.emptylayout)
  private LinearLayout emptylayout;
  @InjectView(id = R.id.reloadRippleView)
  private RippleView reloadRippleView;

  private PrivateStoryAdapter adapter;
  private int mLastpage = 1;
  private ArrayList<CarlaClassicVo> mAdapterList = null;
  private ArrayList<CarlaClassicVo> mArrayList = null;
  public boolean isrefreshlist = false;
  private LeUser leUser;
  private String title;
  private int category_id = -1;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.privatestory);
    setTitle(getIntent().getStringExtra("titles"));

    bindService();
    getDeviceView().setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (LeConfig.isLogin) {
//          startActivity(new Intent(PrivateStoryActivity.this,
//              DevicePropertyActivity.class));
        } else {
          Intent intent0 = new Intent(PrivateStoryActivity.this,
              LoginActivity.class);
          intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          startActivity(intent0);
        }
      }
    });

    initialize();
    initListener();
    requestData1(true);

//    TIMManager.getInstance().setConnectionListener(new TIMConnListener() {
//
//      @Override
//      public void onWifiNeedAuth(String arg0) {
//        // TODO Auto-generated method stub
//
//      }
//
//      @Override
//      public void onDisconnected(int arg0, String arg1) {
//        LeConfig.isDeviceConnect = false;
//
//        if (getDeviceView() != null) {
//          getDeviceView().setPlaying(false);
//        }
//      }
//
//      @Override
//      public void onConnected() {
//        // TODO Auto-generated method stub
//
//      }
//    });
  }

  @Override
  protected void onRestart() {
    if (!LeConfig.isDeviceConnect) {
      if (getDeviceView() != null) {
        getDeviceView().setPlaying(false);
      }
    }

    super.onRestart();
  }

  private void initialize() {
    mAdapterList = new ArrayList<>();
    mArrayList = new ArrayList<>();
    leUser = MyTeacherApp.getInstance().getUserTeacher();
    title = getIntent().getStringExtra("titles");
    category_id = getIntent().getIntExtra("category_id", -1);
  }

  private void initListener() {
    pullToRefreshLayout.setOnRefreshListener(this);
    gridView.setOnItemClickListener(this);
    reloadRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            mLastpage = 1;
            isrefreshlist = true;
            requestData1(true);
          }
        });
  }

  private void requestData1(boolean isShow) {

    if (isShow) {
      showloading("加载中..");
    }
    new CustomAsyncTask(PrivateStoryActivity.this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();
        if (result.isSuccess()) {
          if (mAdapterList != null)
            mAdapterList.clear();
          if (isrefreshlist) {
            if (mArrayList == null) {
              mArrayList = new ArrayList<>();
            }
            mArrayList.clear();
          }
          try {
            if (title.equals("热门推荐")) {
              ArrayList<LeHotRecomStory> remmendStroyList = (ArrayList<LeHotRecomStory>) JsonSerializer
                  .getInstance().deserialize(result.data, ArrayList.class,
                      LeHotRecomStory.class);
              mAdapterList = convert2CarlaClassicVoList(remmendStroyList);
            } else {
              JSONObject jsonObject = new JSONObject(result.data);
              mAdapterList = (ArrayList<CarlaClassicVo>) JsonSerializer
                  .getInstance().deserialize(jsonObject.optString("data"),
                      ArrayList.class, CarlaClassicVo.class);
            }
          } catch (JSONException e) {

          }
          if (mArrayList == null) {
            mArrayList = new ArrayList<>();
          }

          if (mAdapterList != null) {
            mArrayList.addAll(mAdapterList);
          }
          setView();
        } else {
          toastShow(result.data.toString());
          pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
          pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("page", mLastpage);
        if (title.equals("热门推荐")) {
          return HttpUtils.startRequest(HttpUtils.HOST_API
              + "/api/2.0/catalog/story/recommand", param_,
              HttpUtils.TAG_GET_REQUEST);
        } else {
          param_.put("catalog", "dub");
          param_.put("page", mLastpage);
          if (category_id != -1)
            param_.put("category_id", category_id);
          return HttpUtils.startRequest(HttpUtils.HOST_API
              + HttpUtils.GET_STORY_LIST, param_, HttpUtils.TAG_GET_REQUEST);
        }
      }
    }).execute();
  }

  /**
   * @param rommendStroyList
   * @return
   */
  protected ArrayList<CarlaClassicVo> convert2CarlaClassicVoList(
      ArrayList<LeHotRecomStory> recommendStroyList) {

    if (recommendStroyList == null || recommendStroyList.size() == 0)
      return null;
    ArrayList<CarlaClassicVo> carlaClassicVoList = new ArrayList<CarlaClassicVo>();
    int size = recommendStroyList.size();
    int i = 0;
    for (; i < size; i++) {
      LeHotRecomStory lhr = recommendStroyList.get(i);
      CarlaClassicVo ccv = new CarlaClassicVo();
      ccv.id = lhr.id; // );
      ccv.category_id = lhr.category_id; // );
      ccv.catalog = lhr.catalog; // );
      ccv.name = lhr.name; // );
      ccv.cover = lhr.cover;// );
      ccv.url = lhr.url;// );
      ccv.enabled = lhr.enabled; // );
      ccv.sort = lhr.sort; // );
      ccv.length = lhr.length; // );
      ccv.agefrom = 0; // );
      ccv.ageto = 0;
      ccv.lines = lhr.lines; // );
      ccv.created_at = lhr.created_at; // );
      ccv.updated_at = lhr.updated_at; // );
      ccv.deleted_at = lhr.deleted_at; // );
      ccv.followers = lhr.followers;// );
      ccv.corner_icon = lhr.corner_icon; // );
      ccv.author = lhr.author; // );
      ccv.tags = lhr.tags; // );

      // ccv.setId(lhr.id);
      // ccv.setCategory_id(lhr.category_id);
      // ccv.setCatalog(lhr.catalog);
      // ccv.setName(lhr.name);
      // ccv.setCover(lhr.cover);
      // ccv.setUrl(lhr.url);
      // ccv.setEnabled(lhr.enabled);
      // ccv.setSort(lhr.sort);
      // ccv.setLength(lhr.length);
      // ccv.setAgefrom(0);
      // ccv.setAgeto(0);
      // ccv.setLines(lhr.lines);
      // ccv.setCreated_at(lhr.created_at);
      // ccv.setUpdated_at(lhr.updated_at);
      // ccv.setDeleted_at(lhr.deleted_at);
      // ccv.setFollowers(lhr.followers);
      // ccv.setCorner_icon(lhr.corner_icon);
      // ccv.setAuthor(lhr.author);
      // ccv.setTags(lhr.tags);
      carlaClassicVoList.add(ccv);
    }
    return carlaClassicVoList;
  }

  private void setView() {
    if (adapter == null) {
      adapter = new PrivateStoryAdapter(this, mArrayList);
      gridView.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
      pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
      // pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
    if (adapter.getCount() == 0) {
      emptylayout.setVisibility(View.VISIBLE);
    } else {
      emptylayout.setVisibility(View.GONE);
    }
  }

  @Override
  public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
    mLastpage = 1;
    isrefreshlist = true;
    requestData1(false);
  }

  @Override
  public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
    mLastpage++;
    isrefreshlist = false;
    requestData1(false);
  }

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//    Intent recode = new Intent();
//    Bundle bundle = new Bundle();
//    bundle.putSerializable("carlaclassic", mArrayList.get(arg2));
//    recode.putExtras(bundle);
//    recode.setClass(this, RecordActivity.class);
//    startActivity(recode);
    // recode.putExtra("id", 5);
    // recode.putExtra("name", "名落孙山");
    // recode.putExtra("lines", "ar佚名");
    // recode.putExtra("reslen", "219");
    // recode.putExtra("url",
    // "http: //res.zhuanzhuan888.com/peiyinstory-mp4/成语故事/名落孙山.mp4");
    // recode
    // .putExtra("pic2", "http: //api.zhuanzhuan888.com//simg/名落孙山/pic2.jpg");
  }

  @Override
  public void onRemoteLogin() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (getDeviceView() != null) {
          getDeviceView().setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onConnectionChanged(boolean connect) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

//  private ImHelper mImHelper;

  private void bindService() {

//    mImHelper = MyTeacherApp.getInstance().getImHelper();
//    if (mImHelper != null && mImHelper.isLogin()) {
//      mImHelper.setOnDataReceivedListener(this);
//      mImHelper.setIMParseListener(this);
//
//      try {
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("code", "app");
//        dataJson.put("act", "machineinfo");
//        mImHelper.send(dataJson.toString());
//      } catch (JSONException e) {
//        e.printStackTrace();
//      } catch (Exception e) {
//        e.printStackTrace();
//      }
//    }

  }

  @Override
  protected void onDestroy() {
//    if (mImHelper != null) {
//      mImHelper.removeDataReceivedListener(this);
//      mImHelper.removeIMParseListener(this);
//    }

    super.onDestroy();
  }

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          JSONObject data) {

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (playState.equals(PlayState.Playing)) {
          getDeviceView().setPlaying(true);
        } else {
          getDeviceView().setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onDataReceived(String data) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onNetWorkDisconn() {
    if (getDeviceView() != null) {
      getDeviceView().setPlaying(false);
    }

  }
}
